import { ref } from 'vue'
import { defineStore } from 'pinia'
import { type RouteLocationNormalized } from 'vue-router'
import { type IRouterMenu } from '@/router/interface'
import { routes } from '@/config'
import router from '@/router'

/** 状态管理 */
export const useStore = defineStore('use_store', () => {
  /** 获取路由菜单数据 */
  const _getRouterMenu = (keep: boolean = true): IRouterMenu[] => {
    const arr = JSON.parse(JSON.stringify(routes[1].children))
    _getRouterMenuRecursion(arr, keep)
    return arr
  }
  /** 递归获取路由菜单数据 */
  const _getRouterMenuRecursion = (arr: any[], keep: boolean = true): void => {
    arr.forEach((value: any) => {
      /** 判断是否永久缓存 */
      if (keep && value.meta?.keep) {
        const index = routerInclude.value.indexOf(value.name)
        if (index < 0) {
          routerInclude.value.push(value.name)
        }
      }

      /** 删除指定元素 */
      delete value.component
      delete value.redirect

      /** 判断是否有子路由 */
      if (value.children && value.children.length > 0) {
        _getRouterMenuRecursion(value.children, keep)
      }
    })
  }

  /** 当前缓存的路由 */
  const routerInclude = ref<string[]>([])
  /** 页面菜单数据 */
  const pageMenu = ref(_getRouterMenu())
  /** 页面标签数据 */
  const pageTabs = ref<IRouterMenu[]>([pageMenu.value[0]])

  /** 开启页面标签 */
  const PageTabsOpen = (to: RouteLocationNormalized) => {
    if (to.meta?.title && to.name) {
      let inTabs = false

      /** 判断标签组有没有此路由标签 */
      for (let index = 0; index < useStore().pageTabs.length; index++) {
        if (useStore().pageTabs[index].name === to.name) {
          inTabs = true
          break
        }
      }

      /** 如果标签没有就添加 */
      if (!inTabs) {
        let include: boolean = true
        for (let i = 0; i < routerInclude.value.length; i++) {
          if (to.name === routerInclude.value[i]) {
            include = false
            break
          }
        }
        if (include) {
          routerInclude.value.push(<string>to.name)
        }

        pageTabs.value.push({
          name: <string>to.name,
          path: to.path,
          meta: <any>to.meta
        })
      }
    }
  }

  /** 关闭页面标签 */
  const PageTabsClose = (path: string, replace: boolean) => {
    let name = ''

    for (let i = 0; i < pageTabs.value.length; i++) {
      if (pageTabs.value[i].path === path) {
        if (!pageTabs.value[i].meta?.keep) {
          const index = routerInclude.value.indexOf(pageTabs.value[i].name)
          routerInclude.value.splice(index, 1)
        }
        pageTabs.value.splice(i, 1)
        name = pageTabs.value[i - 1].name
        break
      }
    }

    if (name && replace) {
      router.replace({ name })
    }
  }

  return {
    routerInclude,
    pageTabs,
    pageMenu,
    PageTabsOpen,
    PageTabsClose
  }
})
